package priv.tuyou.system.serviceImpl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import priv.tuyou.constants.WebContext;
import priv.tuyou.dao.IDao;
import priv.tuyou.exception.ServiceException;
import priv.tuyou.system.dao.ISystemUserDao;
import priv.tuyou.system.po.SystemUser;
import priv.tuyou.system.service.ISystemUserService;
import priv.tuyou.util.ResourceUtil;

@Service
public class SystemUserServiceImpl implements ISystemUserService{

	@Resource
	protected IDao dao;
	@Resource
	protected ISystemUserDao systemUserDao;
	
	@Override
	public SystemUser login(String username, String password) throws ServiceException {
		
		if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
			
			throw new ServiceException(ResourceUtil.getText("user.name.and.password.is.require"));
		}
		
		SystemUser user = systemUserDao.getByName(username);
		if(user == null){
			
			throw new ServiceException(ResourceUtil.getText("user.name.not.exists"));
		}
		
		password = DigestUtils.md5Hex(password);
		if(!user.getPassword().equalsIgnoreCase(password)){
			
			throw new ServiceException(ResourceUtil.getText("user.password.incorret"));
		}
		
		WebContext.setSystemUser(user);
		return user;
	}
	
	@Override
	public SystemUser add(String username, String password, String nickname, String phone) throws ServiceException {

		//检测登录名是否重复
		if(systemUserDao.getByName(username) != null){
			
			throw new ServiceException("系统存在相同的登录名，不可重复注册");
		}
		
		SystemUser user = new SystemUser();
		user.setUsername(username);
		user.setPassword(DigestUtils.md5Hex(password));
		user.setNickname(nickname);
		user.setPhone(phone);
		dao.save(user);
		return null;
	}
	
	@Override
	public SystemUser update(Long id, String username, String nickname, String phone) throws ServiceException {

		SystemUser user = dao.get(SystemUser.class, id);
		
		//检测登录名是否重复
		SystemUser getUser = systemUserDao.getByName(username);
		if(getUser != null){
			
			if(!username.equals(user.getUsername()) && username.equals(getUser.getUsername())){
				
				throw new ServiceException("系统存在相同的登录名，不可重复注册");
			}
		}
		
		user.setUsername(username);
		user.setNickname(nickname);
		user.setPhone(phone);
		dao.update(user);
		return user;
	}

	@Override
	public boolean update(Long id, String password) throws ServiceException {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("password", DigestUtils.md5Hex(password));
		int effect = dao.update(SystemUser.class, id, map);
		return effect > 0 ? true : false;
	}
}
